<template>
    <view class="shop-page">
        <!-- 店铺信息 -->
        <view class="shop-info" >
            <!-- 店铺Logo和店铺名称/关注按钮在一行 -->
            <view class="info-row1">
                <image :src="shopInfo.shopLogo" class="shop-logo" alt="店铺Logo" />
                <view class="shop-header">
                    <text class="shop-name">{{ shopInfo.shopName }}</text>
                    <button class="follow-btn" @click="updataShop" style="width: 100px;">修改</uni-icons></button>
                </view>
            </view>

            <!-- 介绍和其他信息的分行布局 -->
            <view class="shop-details">
                <text class="description">{{ shopInfo.shopDescription }}</text>
                <view class="info-row2">
                    <text class="shop-rating">评分：{{ shopInfo.shopRating }}</text>
                    <!-- 使用星星图标表示等级 -->
                    <view class="shop-level">等级：
                             <view  v-for="i in shopInfo.shopLevel" :key="i">
                               <uni-icons class="icons" type="star-filled" size="15" color="#ff9900"></uni-icons></view>
                             </view>
                    <text class="shop-status">
                        状态：{{ shopInfo.shopStatus === '0' ? '营业中' : '暂停营业' }}
                    </text>
                </view>
            </view>
        </view>
        
		<view class="sort-dropdown">
		    <text @click="openSalesDrawer">销量</text>
		    <text @click="openPriceDrawer">价格</text>
		</view>
        <!-- 商品部分 -->
        <scroll-view class="product-scroll" scroll-y="true" show-scrollbar="true">
            <view class="product-row">
                <view v-for="(item, index) in productList" :key="index" class="product-item">
                    <view @click="goToGoodsdetail(item.productId)">
                        <product class="product-card"
                            :imageUrl="getPrimaryImageUrl(item.images)"
                            :title="item.productName"
                            :price="item.price"
                            :unit="item.unit"
                            :productId="item.productId"
                        />
                    </view>
					<view class="button-updata">
					<button type="warn" @click="openDeletePopup(item.productId)">删除</button>
					<button type="primary"@click="updataProduct(item)">修改</button>
					</view>
                </view>
            </view>
        </scroll-view>


		<!-- 销量排序抽屉 -->
		<uni-popup ref="salesPopup" type="top" background-color="white" v-model="showSalesDrawer">
		    <view class="popup-content">
		        <view v-for="(option, index) in sortOptions" :key="index" @click="onSortChange(index)" class="popup-item">
		            {{ option }}
		        </view>
		    </view>
		</uni-popup>
		
		<!-- 价格筛选抽屉 -->
		<uni-popup ref="pricePopup" type="top" background-color="white" v-model="showPriceDrawer">
		  <view class="drawer-content">
			  <view v-for="(option, index) in sortOptions" :key="index" class="price-option">
			    <view @click="onSortChange(index + 2)" >
			      {{ option }}
			    </view>
			  </view>
		    <text class="drawer-title">选择价格区间</text>
		    <view class="price-input">
		      <input type="number" v-model="priceMin" placeholder="最低价格" />
		      <text>—</text>
		      <input type="number" v-model="priceMax" placeholder="最高价格" />
		    </view>
		    <view class="drawer-actions">
		      <button @click="closePriceDrawer">关闭</button>
		      <button @click="applyPriceFilter">确认</button>
		    </view>
		  </view>
		</uni-popup>
		
		<!-- 删除确认弹窗 -->
		<uni-popup ref="deletePopup" type="dialog">
		  <view class="popup-content">
		    <text class="confirm-text">确定要删除该商品吗？</text>
		    <view class="popup-buttons">
		      <button type="default" class="cancel-button" @click="cancelDelete">取消</button>
		      <button type="warn" class="confirm-button" @click="confirmDelete">确认</button>
		    </view>
		  </view>
		</uni-popup>
    </view>
</template>

<script>
import { getShopDetail, getShopProducts } from '../../../api/shop/index.js';
import {deleteProduct}from'@/api/home/goods.js'

export default {
    
    data() {
        return {
			userId:null,
            shopInfo: {}, 
            productList: [],
            sortOptions: ['取消', '从高到低', '从低到高'],
            priceMin: null,
            priceMax: null,
            selectedSortIndex: 0,
			deleteProductId:null,
        }
    },
    onLoad(options) {
        this.userId = options.userId;
        if (this.userId) {
            this.getShopInfo(this.userId);
        } 
    },
    methods: {
        async getShopInfo(userId) {
            try {
                const data = await getShopDetail(this.userId);
                this.shopInfo = data;
                await this.getShopProducts();
            } catch (error) {
                console.error("获取店铺信息失败:", error);
            }
        },
        async getShopProducts() {
            if (this.shopInfo && this.shopInfo.shopId) {
                try {
                    const data = await getShopProducts(this.shopInfo.shopId,this.selectedSortIndex,this.priceMin,this.priceMax);
                    this.productList = data;
                } catch (error) {
                    console.error("获取商品列表失败:", error);
                }
            }
        },
  getPrimaryImageUrl(images) {
     if (!images || images.length === 0) {
       // 返回默认动态图片路径
       return '/static/home/dj.jpg'; // 默认图片的 URL
     }
    
     const primaryImage = images.find(image => image.isPrimary);
     // 返回主图 URL 或第一张图片的 URL，如果都没有，则返回默认图片
     return primaryImage?.imageUrl || images[0]?.imageUrl || '/static/home/dj.jpg';
   },
        onSortChange(index) {
            this.selectedSortIndex = index;
            this.getShopProducts(); // 切换排序时，重新加载商品
        },
        // 打开销量排序抽屉
          openSalesDrawer() {
            this.$refs.salesPopup.open()
          },
        
          // 打开价格筛选抽屉
          openPriceDrawer() {
            this.$refs.pricePopup.open()
          },
          // 关闭价格筛选抽屉
          closePriceDrawer() {
            this.$refs.pricePopup.close();
          },
        
          // 应用价格筛选
          applyPriceFilter() {
        	  console.log(this.priceMin)
            this.getShopProducts(); // 应用价格筛选后重新加载商品
            this.closePriceDrawer(); // 关闭价格筛选抽屉
          },

        contactSupport() {
            uni.showToast({ title: '联系客服', icon: 'none' });
        },
        callPhone() {
            uni.makePhoneCall({ phoneNumber: '123456789' });
        },
	  // 修改店铺信息
	    updataShop() {
	        const shopData = encodeURIComponent(JSON.stringify(this.shopInfo));
	        uni.navigateTo({
	            url: `/pages/shop/updata/updata?shopInfo=${shopData}`
	        });
	    },
	    // 修改商品信息
	    updataProduct(product) {
	        const productData = encodeURIComponent(JSON.stringify(product));
	        uni.navigateTo({
	            url: `/pages/product/updata/updata?productInfo=${productData}`
	        });
	    },
		// 打开删除确认弹窗
		 openDeletePopup(productId) {
		
		   this.$refs.deletePopup.open();
		   this.deleteProductId=productId
		 },
			
		 // 取消删除
		 cancelDelete() {
			 this.deleteProductId=null;
		   this.$refs.deletePopup.close();
		 },
		 //确认删除
		confirmDelete(){
			if(!this.deleteProductId){
				uni.showToast({
					title:"删除失败",
					icon:"none"
				})
			}
			deleteProduct(this.deleteProductId)
			uni.showToast({
				title:"删除成功",
				icon:"none"
			})
			 this.getShopProducts()
			 this.$refs.deletePopup.close();
		}
    }
}
</script>


<style lang="scss">
.shop-page {
    margin: 8rpx;
    background-color: #f5f5f5;
}

.shop-info {
    border-radius: 20rpx;
    background-color: #00aa7f;
    padding: 20rpx;
    color: white;

    .info-row1 {
        display: flex;
        align-items: center;
        margin-bottom: 10rpx;

        .shop-logo {
            width: 120rpx;
            height: 120rpx;
            border-radius: 60rpx;
        }

        .shop-header {
            flex: 1;
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-left: 10rpx;

            .shop-name {
                font-size: 36rpx;
                font-weight: bold;
            }

            .follow-btn {
                margin-left: 120rpx;
                background-color: #ffaa00;
                padding: 10rpx 20rpx;
                border-radius: 10rpx;
            }
        }
    }

    .shop-details {
        font-size: 28rpx;

        .description {
            margin: 10rpx 4rpx;
        }

        .info-row2 {
            display: flex;
            justify-content: space-between;
            margin-top: 10rpx;
        }
    }
}

.shop-level {
    display: flex;
    align-items: center;
}

.footer {
    display: flex;
    justify-content: space-between;
    padding: 10rpx;
    background-color: #fff;

    .footer-btn {
        flex: 1;
        padding: 5rpx;
        font-size: 16rpx;
        text-align: center;
        border-radius: 5rpx;
        background-color: #00aaff;
        border: 1rpx solid #32CD32;
    }
}

.sort-dropdown {
    display: flex;
    justify-content: space-around;
    align-items: center;
    width: 100%;
    height: 50rpx;
    background-color: #fff;
    border-bottom: 1rpx solid #eee;

    text {
        font-size: 16rpx;
        color: #333;
        cursor: pointer;
    }
}

.product-scroll {
    height: 1200rpx;
    overflow-y: auto;
}

.product-row {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    padding: 10rpx;
}

.product-item {
    width: 46%;
    margin-bottom: 10rpx;
    box-sizing: border-box;
}

.product-card {
    width: 100%;
    background-color: #fff;
    border-radius: 8rpx;
    box-shadow: 0 2rpx 5rpx rgba(0, 0, 0, 0.1);
    overflow: hidden;
}

.button-updata {
    display: flex;
    justify-content: space-between;
    margin-top: 10rpx;
}

button {
    flex: 1;
    margin: 0 5rpx;
}

.popup-content,
.drawer-content {
    padding: 16rpx;
}

.price-option {
    border-bottom: 1rpx solid #e0e0e0;
    padding: 12rpx 0;
    display: flex;
    align-items: center;
    justify-content: center;
}

.popup-item,
.price-input,
.drawer-actions {
    border-bottom: 1rpx solid #e0e0e0;
    padding: 12rpx 0;
    display: flex;
    align-items: center;
    justify-content: center;
}

.popup-item,
.drawer-title,
.price-input text {
    font-weight: bold;
    text-align: center;
}

.price-input {
    display: flex;
    align-items: center;
    justify-content: space-around;
    padding: 5rpx 0;
}

.price-input input {
    width: 40%;
    height: 50rpx;
    padding: 5rpx;
    border: 1rpx solid #ddd;
    border-radius: 4rpx;
    font-size: 15rpx;
    text-align: center;
}

.drawer-actions button {
    flex: 1;
    padding: 2rpx;
    margin: 0 8rpx;
    font-size: 12rpx;
    color: white;
    font-weight: bold;
    border-radius: 4rpx;
    text-align: center;
}

.drawer-actions button:first-child {
    background-color: #00aa00;
}

.drawer-actions button:last-child {
    background-color: #007aff;
}

.popup-content {
    background-color: #f0f0f0;
    padding: 20rpx;
    text-align: center;
}

.confirm-text {
    font-size: 16rpx;
    color: #333;
    margin-bottom: 20rpx;
}

.popup-buttons {
    margin-top: 20rpx;
    display: flex;
    justify-content: space-between;
}

.cancel-button,
.confirm-button {
    flex: 1;
    padding: 10rpx;
    margin: 0 8rpx;
    font-size: 14rpx;
    border-radius: 4rpx;
}

.cancel-button {
    background-color: #00aa00;
    color: #333;
}

.confirm-button {
    background-color: #ff4d4f;
    color: white;
}

.button-updata {
    display: flex;
    justify-content: space-center;
}


</style>
